<?php
namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use Illuminate\Http\Request;

class AccountController extends Controller
{
    /**
     * 登录
     *
     * @param Request $request
     * @return Response
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'username' => 'required',
            'password' => 'required',
        ], [
            'required' => ':attribute不能为空',
        ], [
            'username' => '用户名',
            'password' => '密码',
        ]);

        if (!$user = $this->hasValidCredentials($request)) {
            return invalidation('用户名或密码错误');
        }

        return [
            'username' => $user->username,
            'api_token' => $user->api_token,
        ];
    }

    /**
     * 验证账号、密码是否正确，是的话，返回Admin对象
     *
     * @param Request $request
     * @return bool|Admin
     */
    protected function hasValidCredentials(Request $request)
    {
        $inputs = $request->only('username', 'password');
        $user = Admin::where('username', $inputs['username'])->first();

        if (!is_null($user) && app('hash')->check($inputs['password'], $user->getAuthPassword())) {
            return $user;
        }

        return false;
    }

    public function logout(){
    	
    }

    /**
     * 账户信息
     *
     * @param Request $request
     * @return Response
     */
    public function show(Request $request)
    {
        $user = $request->user('admin');
        return $user->toArray() + [
        	'roles' => ['admin']
        ];
    }
}
